import sys
import json
import socket
import urllib, json, urllib2, hashlib,struct,sha,time
import smtplib  
from email.mime.text import MIMEText  
from email.header import Header  
import time
import common as bbc

if __name__ == '__main__':
    socket.setdefaulttimeout(60)
    sendTimestamp = 0
    flag = False
    while True:
        try:
            diff = bbc.getDifferenceRateBHKraken()
        except BaseException:
            print "Network Error"
        else:
            if diff['xrp']['rate'] > 0.035 and flag == False:
                flag = True
                if (int(time.time()) - sendTimestamp) > 5*60:
                    try:
                        bbc.sendEmail("wluhan@foxmail.com", "Time to buy xrp from kraken", json.dumps(diff))
                        bbc.sendEmail("809484424@qq.com", "Time to buy xrp from kraken", json.dumps(diff))
                    except BaseException:
                        print "Send email Error"
                    else:
                        sendTimestamp = int(time.time())
                        print "Sending email"
                else:
                    print "Already sent...too small time gap"
	    elif diff['xrp']['rate'] < 0.01 and flag == True:
                flag = False
		if (int(time.time()) - sendTimestamp) > 60:
                    try:
                        bbc.sendEmail("wluhan@foxmail.com", "Time to transfer xrp to kraken", json.dumps(diff))
                        bbc.sendEmail("809484424@qq.com", "Time to transfer xrp to kraken", json.dumps(diff))
                    except BaseException:
                        print "Send email Error"
                    else:
                        sendTimestamp = int(time.time())
                        print "Sending email"
                else:
                    print "Already sent...too small time gap"
		
            else:
		print time.asctime( time.localtime(time.time()) )+"---Current xrp  rate is:" + str(diff['xrp']['rate'])
		print time.asctime( time.localtime(time.time()) )+"---Current eth  rate is:" + str(diff['eth']['rate'])
                print "not right time to buy"
        time.sleep(10)

    
